<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发送短信验证码</title>
<script>
let isPhoneSent = false; // 用于跟踪手机号是否已发送
async function sendPhoneNumber() {
    var phoneNumber = document.getElementById("phoneNumber").value;  
    var selectedOption = document.querySelector('input[name="option"]:checked').value;
    if (phoneNumber) {
        try {
            const response = await fetch("/submit_phone", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `phone=${encodeURIComponent(phoneNumber)}&option=${encodeURIComponent(selectedOption)}`
            });

            if (response.ok) {
                const data = await response.json();
                alert(`状态: ${data.status}\n消息: ${data.message}`);
                if(data.status=="ok"){
                    isPhoneSent = true      
                    enableSendCodeButton();  
                }
               
            } else {
                throw new Error('Network response was not ok.');
            }
        } catch (error) {
            alert("发送失败，请重试。");
        }
    } else {
        alert("请输入手机号码！");
    }
}
async function Code() {
    var phoneNumber = document.getElementById("phoneNumber").value;  
    var code = document.getElementById("code").value;
    if (code && phoneNumber && isPhoneSent) {
        try {
            const response = await fetch("/validate", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `phone=${encodeURIComponent(phoneNumber)}&code=${encodeURIComponent(code)}`
            });

            if (response.ok) {
                const data = await response.json();
                alert(`状态: ${data.status}\n消息: ${data.message}`);
            } else {
                throw new Error('Network response was not ok.');
            }
        } catch (error) {
            alert("发送失败，请重试。");
        }
    } else {
        alert("请输入验证码");
    }
}
function enableSendCodeButton() {
    document.getElementById("sendCodeButton").disabled = false;
}
</script>
</head>
<body>
<h1>填写手机号发送验证码</h1>
<div>
    <input type="radio" id="option1" name="option" value="阿里" checked required>
    <label for="option1">选择阿里发送短信</label><br>
    <input type="radio" id="option2" name="option" value="腾讯" required>
    <label for="option2">选择腾讯发送短信</label><br>
</div>
<input type="text" id="phoneNumber" placeholder="请输入手机号码" />
<button onclick="sendPhoneNumber()">发送</button>
<p>&nbsp;</p>
<input type="text" id="code" placeholder="输入验证码" />
<button id="sendCodeButton"  onclick="Code()" disabled>验证</button>
</body>
</html>